from flask import Blueprint, request, jsonify
from models import User, Course, db, SystemLog
from utils import hash_password, format_response
from decorators import admin_required, teacher_required
from flask_jwt_extended import get_jwt_identity

admin_bp = Blueprint('admin', __name__)

@admin_bp.route('/users', methods=['GET'])
@teacher_required
def get_users():
    """获取所有用户"""
    try:
        # 获取查询参数
        role = request.args.get('role')
        status = request.args.get('status')
        department = request.args.get('department')
        
        # 构建查询
        query = User.query
        
        if role:
            query = query.filter(User.role == role)
        if status:
            query = query.filter(User.status == status)
        if department:
            query = query.filter(User.department.contains(department))
        
        users = query.all()
        return jsonify(format_response([user.to_dict() for user in users]))
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@admin_bp.route('/users/<int:user_id>', methods=['GET'])
@teacher_required
def get_user(user_id):
    """获取指定用户"""
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify(format_response(message="用户不存在", code=404)), 404
        return jsonify(format_response(user.to_dict()))
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@admin_bp.route('/users', methods=['POST'])
@teacher_required
def create_user():
    """创建用户"""
    try:
        data = request.get_json()
        current_admin_id = get_jwt_identity()
        
        # 必需字段
        username = data.get('username')
        password = data.get('password')
        name = data.get('name')
        role = data.get('role', 'student')
        
        if not username or not password or not name:
            return jsonify(format_response(message="用户名、密码和姓名不能为空", code=400)), 400
        
        # 检查用户名是否已存在
        if User.query.filter_by(username=username).first():
            return jsonify(format_response(message="用户名已存在", code=400)), 400
        
        # 检查邮箱是否已存在
        email = data.get('email')
        if email and User.query.filter_by(email=email).first():
            return jsonify(format_response(message="邮箱已存在", code=400)), 400
        
        hashed_password = hash_password(password)
        new_user = User(
            username=username,
            email=email,
            password=hashed_password,
            name=name,
            role=role,
            department=data.get('department'),
            status=data.get('status', 'active')
        )
        
        db.session.add(new_user)
        db.session.commit()
        
        # 记录系统日志
        log = SystemLog(
            type='info',
            message=f'管理员创建了新用户: {username}',
            user_id=current_admin_id
        )
        db.session.add(log)
        db.session.commit()
        
        return jsonify(format_response(new_user.to_dict(), "用户创建成功"))
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@admin_bp.route('/users/<int:user_id>', methods=['PUT'])
@teacher_required
def update_user(user_id):
    """更新用户"""
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify(format_response(message="用户不存在", code=404)), 404
        
        data = request.get_json()
        
        # 更新基本字段
        if 'username' in data:
            # 检查用户名是否已被其他用户使用
            existing_user = User.query.filter_by(username=data['username']).first()
            if existing_user and existing_user.id != user_id:
                return jsonify(format_response(message="用户名已存在", code=400)), 400
            user.username = data['username']
        
        if 'email' in data:
            # 检查邮箱是否已被其他用户使用
            if data['email']:
                existing_user = User.query.filter_by(email=data['email']).first()
                if existing_user and existing_user.id != user_id:
                    return jsonify(format_response(message="邮箱已存在", code=400)), 400
            user.email = data['email']
        
        if 'name' in data:
            user.name = data['name']
        
        if 'role' in data:
            user.role = data['role']
        
        if 'department' in data:
            user.department = data['department']
        
        if 'status' in data:
            user.status = data['status']
        
        if 'password' in data and data['password']:
            user.password = hash_password(data['password'])
        
        db.session.commit()
        return jsonify(format_response(user.to_dict(), "用户更新成功"))
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@admin_bp.route('/users/<int:user_id>', methods=['DELETE'])
@teacher_required
def delete_user(user_id):
    """删除用户"""
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify(format_response(message="用户不存在", code=404)), 404
        
        # 软删除：将状态设置为inactive
        user.status = 'inactive'
        db.session.commit()
        
        return jsonify(format_response(message="用户删除成功"))
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@admin_bp.route('/users/<int:user_id>/reset-password', methods=['POST'])
@admin_required
def reset_user_password(user_id):
    """重置用户密码"""
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify(format_response(message="用户不存在", code=404)), 404
        
        # 重置为默认密码
        default_password = '123456'
        user.password = hash_password(default_password)
        db.session.commit()
        
        return jsonify(format_response(message=f"用户密码已重置为: {default_password}"))
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@admin_bp.route('/users/<int:user_id>/status', methods=['PUT'])
@teacher_required
def change_user_status(user_id):
    """更改用户状态"""
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify(format_response(message="用户不存在", code=404)), 404
        
        data = request.get_json()
        new_status = data.get('status')
        
        if new_status not in ['active', 'inactive', 'banned']:
            return jsonify(format_response(message="无效的状态值", code=400)), 400
        
        user.status = new_status
        db.session.commit()
        
        return jsonify(format_response(message=f"用户状态已更改为: {new_status}"))
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@admin_bp.route('/teachers', methods=['GET'])
@admin_required
def get_teachers():
    """获取所有教师及其课程"""
    try:
        teachers = User.query.filter_by(role='teacher').all()
        result = []
        for teacher in teachers:
            courses = Course.query.filter_by(teacher_id=teacher.id).all()
            teacher_data = teacher.to_dict()
            teacher_data['courses'] = [course.to_dict() for course in courses]
            result.append(teacher_data)
        
        return jsonify(format_response(result))
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@admin_bp.route('/courses', methods=['GET'])
@admin_required
def get_courses():
    """获取所有课程"""
    try:
        courses = Course.query.all()
        return jsonify(format_response([course.to_dict() for course in courses]))
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@admin_bp.route('/courses', methods=['POST'])
@admin_required
def create_course():
    """创建课程"""
    try:
        data = request.get_json()
        
        name = data.get('name')
        code = data.get('code')
        teacher_id = data.get('teacher_id')
        
        if not name or not code or not teacher_id:
            return jsonify(format_response(message="课程名称、代码和教师ID不能为空", code=400)), 400
        
        # 检查课程代码是否已存在
        if Course.query.filter_by(code=code).first():
            return jsonify(format_response(message="课程代码已存在", code=400)), 400
        
        # 检查教师是否存在
        teacher = User.query.get(teacher_id)
        if not teacher or teacher.role != 'teacher':
            return jsonify(format_response(message="指定的教师不存在", code=400)), 400
        
        new_course = Course(
            name=name,
            code=code,
            description=data.get('description'),
            teacher_id=teacher_id,
            status=data.get('status', 'active')
        )
        
        db.session.add(new_course)
        db.session.commit()
        
        return jsonify(format_response(new_course.to_dict(), "课程创建成功"))
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@admin_bp.route('/courses/<int:course_id>', methods=['PUT'])
@admin_required
def update_course(course_id):
    """更新课程"""
    try:
        course = Course.query.get(course_id)
        if not course:
            return jsonify(format_response(message="课程不存在", code=404)), 404
        
        data = request.get_json()
        
        if 'name' in data:
            course.name = data['name']
        
        if 'code' in data:
            # 检查课程代码是否已被其他课程使用
            existing_course = Course.query.filter_by(code=data['code']).first()
            if existing_course and existing_course.id != course_id:
                return jsonify(format_response(message="课程代码已存在", code=400)), 400
            course.code = data['code']
        
        if 'description' in data:
            course.description = data['description']
        
        if 'teacher_id' in data:
            # 检查教师是否存在
            teacher = User.query.get(data['teacher_id'])
            if not teacher or teacher.role != 'teacher':
                return jsonify(format_response(message="指定的教师不存在", code=400)), 400
            course.teacher_id = data['teacher_id']
        
        if 'status' in data:
            course.status = data['status']
        
        db.session.commit()
        return jsonify(format_response(course.to_dict(), "课程更新成功"))
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@admin_bp.route('/courses/<int:course_id>', methods=['DELETE'])
@admin_required
def delete_course(course_id):
    """删除课程"""
    try:
        course = Course.query.get(course_id)
        if not course:
            return jsonify(format_response(message="课程不存在", code=404)), 404
        
        # 软删除：将状态设置为inactive
        course.status = 'inactive'
        db.session.commit()
        
        return jsonify(format_response(message="课程删除成功"))
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@admin_bp.route('/stats', methods=['GET'])
@admin_required
def get_admin_stats():
    """获取管理员统计信息"""
    try:
        # 用户统计
        total_users = User.query.count()
        active_users = User.query.filter(User.status == 'active').count()
        student_count = User.query.filter(User.role == 'student').count()
        teacher_count = User.query.filter(User.role == 'teacher').count()
        
        # 课程统计
        total_courses = Course.query.count()
        active_courses = Course.query.filter(Course.status == 'active').count()
        
        stats = {
            'users': {
                'total': total_users,
                'active': active_users,
                'students': student_count,
                'teachers': teacher_count
            },
            'courses': {
                'total': total_courses,
                'active': active_courses
            }
        }
        
        return jsonify(format_response(stats))
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@admin_bp.route('/logs', methods=['GET'])
@admin_required
def get_system_logs():
    """获取系统日志"""
    try:
        # 获取查询参数
        log_type = request.args.get('type')
        limit = request.args.get('limit', 100, type=int)
        
        query = SystemLog.query.order_by(SystemLog.created_at.desc())
        
        if log_type:
            query = query.filter(SystemLog.type == log_type)
        
        logs = query.limit(limit).all()
        return jsonify(format_response([log.to_dict() for log in logs]))
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500
